//
//  UIView+Style.m
//  ZhaoCaiMao
//
//  Created by xieyingze on 2017/3/13.
//  Copyright © 2017年 谢英泽. All rights reserved.
//

#import "UIView+Style.h"

static NSInteger BlurBlurredImageView = -100; // blurred image view's tag
static NSInteger BlurOverlay          = -101; // overlay's tag

@implementation UIView (Style)

#pragma mark - Blur

- (void)setViewBlurWithRadius:(float)radius {
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage  = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CIContext *context  = [CIContext contextWithOptions:nil];
    
    CIImage *inputImage = [CIImage imageWithCGImage:viewImage.CGImage];
    
    CIFilter *gaussianBlurFilter  = [CIFilter filterWithName:@"CIGaussianBlur"];
    [gaussianBlurFilter setValue:inputImage forKey:@"inputImage"];
    [gaussianBlurFilter setValue:[NSNumber numberWithFloat:radius] forKey:@"inputRadius"];
    CIImage *outputImage          = [gaussianBlurFilter valueForKey:@"outputImage"];
    
    CGImageRef cgImage            = [context createCGImage:outputImage fromRect:self.bounds];
    UIImage *blurredImage         = [UIImage imageWithCGImage:cgImage];
    UIImageView *blurredImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    blurredImageView.tag          = BlurBlurredImageView;
    blurredImageView.image        = blurredImage;
    
    UIView *overlay               = [[UIView alloc] initWithFrame:self.bounds];
    overlay.tag                   = BlurOverlay;
    overlay.backgroundColor       = [UIColor colorWithRed:1.0f
                                                    green:1.0f
                                                     blue:1.0f
                                                    alpha:0.8f];
    
    [self addSubview:blurredImageView];
    [self addSubview:overlay];
}

- (void)setViewBlur {
    [self setViewBlurWithRadius:15.0f];
}

- (void)removeViewBlur {
    [[self viewWithTag:BlurBlurredImageView] removeFromSuperview];
    [[self viewWithTag:BlurOverlay] removeFromSuperview];
}

#pragma mark - 圆角

- (void)setViewTopCornnerRadius:(CGRect)rect cornerRadius:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}


- (void)setViewBottomCornnerRadius:(CGRect)rect cornerRadius:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerBottomRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

#pragma mark - 跟谁键盘移动

- (void)setViewFollowKeyboard {
    [self.superview bringSubviewToFront:self];
    //注册监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

/**
 *  如果self上移之后会遮挡住输入框，则superView上移
 *
 *  @return <#return value description#>
 */
- (CGFloat)getMaxY {
    CGFloat maxY = 0.0;
    for (UIView *sub in self.superview.subviews)
    {
        if (![sub isEqual:self] && [sub isFirstResponder])
        {
            maxY = maxY > CGRectGetMaxY(sub.frame) ? maxY : CGRectGetMaxY(sub.frame);
        }
    }
    return maxY;
}
//键盘出现
- (void)keyboardWillAppear:(NSNotification *)notification {
    [UIView animateWithDuration:
     [[notification.userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] floatValue]
                     animations:^{
                         //键盘移动的frame
                         CGFloat betweenY = [[notification.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].origin.y -
                         [[notification.userInfo objectForKey:@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue].origin.y;
                         CGFloat temp = self.frame.origin.y + betweenY - [self getMaxY];
                         if (temp < 0)
                         {
                             self.superview.transform = CGAffineTransformMakeTranslation(kUI_Zero, temp);
                             self.transform = CGAffineTransformMakeTranslation(kUI_Zero, betweenY - temp);
                         }
                         else self.transform = CGAffineTransformMakeTranslation(kUI_Zero, betweenY);;
                         
                     }];
}
//键盘消失
- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:
     [[notification.userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] floatValue] animations:^{
         self.transform = CGAffineTransformIdentity;
         self.superview.transform = CGAffineTransformIdentity;
     }];
}

- (void)setViewRegistFollowKeyboard {
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 阴影

- (void)setViewShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius {
    self.layer.shadowColor = color.CGColor;
    self.layer.shadowOffset = offset;
    self.layer.shadowRadius = radius;
    self.layer.shadowOpacity = 0.5;
    self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
}

- (void)setViewShadow:(kGradientDirection)direction colors:(NSArray *)colors locations:(NSArray *)locations {
    //先要调用[self.view layoutIfNeeded];
    //  创建 CAGradientLayer 对象
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    //  设置 gradientLayer 的 Frame
    gradientLayer.frame = self.bounds;
    
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = colors;
    
    //  设置三种颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = locations;
    
    if (direction == kGradientDirectionHorizontal) {
        //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(1, 1);
        
    }else if (direction == kGradientDirectionVertical){
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(0, 1);
        
    }else if (direction == kGradientDirectionOpposite){
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1, 1);
    }
    //  添加渐变色到创建的 UIView 上去
    [self.layer addSublayer:gradientLayer];
}

#pragma mark - 渐变色背景

- (void)setViewGradientColor:(NSArray *)colors locations:(NSArray *)locations {
    //先要调用[self.view layoutIfNeeded];
    //  创建 CAGradientLayer 对象
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    //  设置 gradientLayer 的 Frame
    gradientLayer.frame = self.bounds;
    
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = colors;
    
    //  设置三种颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = locations;
    
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0, 1);
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    //  添加渐变色到创建的 UIView 上去
    [self.layer addSublayer:gradientLayer];
}

- (void)setViewGradientColor:(NSArray *)colors frame:(CGRect)frame startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    //渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = colors;
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    gradientLayer.locations = @[@0, @1];
    gradientLayer.frame = frame;
    [self.layer addSublayer:gradientLayer];
}

#pragma mark - 截图

- (UIImage *)getSnapshotImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;
}

- (UIImage *)getSnapshotImageWithSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.5);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;
}

+ (UIImage *)locationImageWithImage:(UIImage *)image {
    UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    bg.layer.cornerRadius = 15;
    bg.layer.masksToBounds = YES;
    bg.backgroundColor = kCOLOR_white;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2, 26, 26)];
    imageView.layer.cornerRadius = 13;
    imageView.layer.masksToBounds = YES;
    imageView.image = image;
    [bg addSubview:imageView];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(30, 30), NO, 0);
    [bg.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;
}

- (UIImage *)getSnapshotImageAfterScreenUpdates:(BOOL)afterUpdates {
    if (![self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        return [self getSnapshotImage];
    }
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:afterUpdates];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;
}

- (NSData *)getSnapshotPDF {
    CGRect bounds = self.bounds;
    NSMutableData *data = [NSMutableData data];
    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);
    CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);
    CGDataConsumerRelease(consumer);
    if (!context) return nil;
    CGPDFContextBeginPage(context, NULL);
    CGContextTranslateCTM(context, 0, bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    [self.layer renderInContext:context];
    CGPDFContextEndPage(context);
    CGPDFContextClose(context);
    CGContextRelease(context);
    return data;
}

#pragma mrk - 尖角

- (void)setViewTopAngle:(CGFloat)offsetTop lineColor:(UIColor *)lineColor {
    UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:CGPointMake(0, offsetTop)];
    [linePath addLineToPoint:CGPointMake(50.f, offsetTop)];
    [linePath addLineToPoint:CGPointMake(50.f+10.f/2, offsetTop-5.f)];
    [linePath addLineToPoint:CGPointMake(50.f+10.f, offsetTop)];
    [linePath addLineToPoint:CGPointMake(kUI_WIDTH, offsetTop)];
    
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGFloat width = scale > 0.0 ? 0.25 / scale : 0.25;
    lineLayer.borderWidth = width;
    lineLayer.fillColor = kCOLOR_clear.CGColor;
    lineLayer.strokeColor = lineColor.CGColor;
    lineLayer.path = linePath.CGPath;
    [self.layer addSublayer:lineLayer];
}

- (void)setViewTopAngle:(CGFloat)offsetTop offsetLeft:(CGFloat)offsetLeft lineColor:(UIColor *)lineColor angleColor:(UIColor *)angleColor {
    UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:CGPointMake(0, offsetTop)];
    [linePath addLineToPoint:CGPointMake(offsetLeft, offsetTop)];
    [linePath addLineToPoint:CGPointMake(offsetLeft+10.f/2, offsetTop-5.f)];
    [linePath addLineToPoint:CGPointMake(offsetLeft+10.f, offsetTop)];
    [linePath addLineToPoint:CGPointMake(kUI_WIDTH, offsetTop)];
    
    CAShapeLayer *lineLayer = [CAShapeLayer layer];
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGFloat width = scale > 0.0 ? 0.25 / scale : 0.25;
    lineLayer.borderWidth = width;
    lineLayer.fillColor = angleColor.CGColor;
    lineLayer.strokeColor = lineColor.CGColor;
    lineLayer.path = linePath.CGPath;
    [self.layer addSublayer:lineLayer];
}

@end
